package com.ocom.nettyxf.config;

import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.CharsetUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 初始化ChannelPipeline
 */
@Component
public class DataAcceptInitializer extends ChannelInitializer<SocketChannel> {
//    private static final StringDecoder DECODER = new StringDecoder(CharsetUtil.UTF_8);
    private static final StringEncoder ENCODER = new StringEncoder(CharsetUtil.UTF_8);

    @Autowired
    private ChannelInboundHandlerAdapter dataAcceptHandler;

    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        ChannelPipeline pipeline = socketChannel.pipeline();

        // TODO Auto-generated method stub

        // 设置编解码器
//        socketChannel.pipeline().addLast(DECODER);
        socketChannel.pipeline().addLast(ENCODER);

        // 添加超时Handler(超时时间20s，可调)
        pipeline.addLast(new IdleStateHandler(120, 0, 0, TimeUnit.SECONDS));

//        pipeline.addLast(new DelimiterBasedFrameDecoder(5 * 1024 * 1024));
//
//        pipeline.addLast(new MyMessageDecoder());//解码器

        // 添加核心Handler
        pipeline.addLast(dataAcceptHandler);
    }

//    @Override
//    protected void initChannel(SocketChannel socketChannel) {
//        ChannelPipeline pipeline = socketChannel.pipeline();
//        ByteBuf bufAck = Unpooled.copiedBuffer("</ack>".getBytes());
//        ByteBuf bufReply = Unpooled.copiedBuffer("</reply>".getBytes());
//        pipeline.addLast(new DelimiterBasedFrameDecoder(5 * 1024 * 1024,bufAck,bufReply));
//        pipeline.addLast(new StringDecoder(StandardCharsets.UTF_8));
//        pipeline.addLast("stringEncoder", new StringEncoder(CharsetUtil.UTF_8));
//        pipeline.addLast(new SimpleChatServerHandler());
//    }

}
